# -*- coding: utf-8 -*-

from flask import request
from flask import abort
from flask import jsonify

from autoscrapy.db.mongo_db import mongoClient
from autoscrapy.utils import log


LOG = log.get_logging(__name__)


class InvaildToken(Exception):
    pass


def get_db():
    return mongoClient('autoscrapy').db

def login(f):

    def wrap_fn(db, **kw):
        # check if vaild
        token = request.form['token']
        if vaild_token(db, token):
            f(db, **kw)
        else:
            raise InvaildToken()

    return wrap_fn

class controllerBase(object):

    DEFAULT_METHODS = ['GET']
    PRE_URL = None

    @classmethod
    def allow_methods(cls):
        return cls.DEFAULT_METHODS

    @classmethod
    def get_name(cls):
        return cls.__name__

    @classmethod
    def get_url(cls):
        return cls.PRE_URL

    def _process_request(self, db, **kw):
        pass

    def __call__(self, **kw):
        try:
            db = get_db()
            ret = self._process_request(db, **kw)
        except Exception as e:
            LOG.exception('controller process error %s', e)
            abort(500)
        if type(ret) == dict:
            ret = jsonify(**ret)
        return ret
